package com.loong.musicdemo.util.dataDeal;

import com.loong.musicdemo.model.User;
import com.loong.musicdemo.util.HostUtil;
import com.loong.musicdemo.util.httpUtil.HttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class FriendsDeal {
    private static final String HOST = HostUtil.getHost();

    /**
     * 通过用户userId获取关注列表
     *
     * @param userId 用户id
     * @return 关注列表
     */
    public static List<User> getFollowers(String userId) {
        List<User> followers = new ArrayList<>();
        String url = HOST + "/user/follows?uid=" + userId;
        String response = HttpUtil.sendReturnOKHttpRequest(url);
        try {
            if (response != null) {
                JSONObject object = new JSONObject(response);
                JSONArray follow = object.getJSONArray("follow");
                for (int i = 0; i < follow.length(); i++) {
                    User user = new User();
                    JSONObject obj = follow.getJSONObject(i);
                    user.setUserId(obj.optString("userId"));
                    user.setNickName(obj.optString("nickname"));
                    user.setGender(obj.optInt("gender"));
                    user.setAvatarUrl(obj.optString("avatarUrl"));
                    user.setSignature(obj.optString("signature", ""));
                    followers.add(user);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return followers;
    }

    public static List<User> getFolloweds(String userId) {
        List<User> followeds = new ArrayList<>();
        String url = HOST + "/user/followeds?uid=" + userId;
        String response = HttpUtil.sendReturnOKHttpRequest(url);
        try {
            if (response != null) {
                JSONObject object = new JSONObject(response);
                JSONArray follow = object.getJSONArray("followeds");
                for (int i = 0; i < follow.length(); i++) {
                    User user = new User();
                    JSONObject obj = follow.getJSONObject(i);
                    user.setUserId(obj.optString("userId"));
                    user.setNickName(obj.optString("nickname"));
                    user.setGender(obj.optInt("gender"));
                    user.setAvatarUrl(obj.optString("avatarUrl"));
                    user.setSignature(obj.optString("signature", ""));
                    followeds.add(user);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return followeds;
    }
}
